package com.example.xunai.controller;

import com.example.xunai.dto.request.conversation.CreateConversationRequest;
import com.example.xunai.dto.response.conversation.ConversationListResponse;
import com.example.xunai.entity.User;
import com.example.xunai.service.conversation.ConversationService;
import com.example.xunai.service.user.UserService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final ConversationService conversationService;

    @PostMapping("/update")
    public ResponseEntity<?> updateUser(@RequestBody UpdateUserRequest request, HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }

        try {
            // 获取最新用户信息
            User user = userService.findById(currentUser.getId());
            if (user == null) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "用户不存在"));
            }

            // 验证当前密码
            if (request.getCurrentPassword() == null || !request.getCurrentPassword().equals(user.getPassword())) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "当前密码错误"));
            }

            // 更新用户信息
            if (request.getUsername() != null && !request.getUsername().equals(user.getUsername())) {
                if (userService.existsByUsername(request.getUsername())) {
                    return ResponseEntity.badRequest().body(Map.of("success", false, "message", "用户名已存在"));
                }
                user.setUsername(request.getUsername());
            }

            if (request.getEmail() != null && !request.getEmail().equals(user.getEmail())) {
                if (userService.existsByEmail(request.getEmail())) {
                    return ResponseEntity.badRequest().body(Map.of("success", false, "message", "邮箱已被注册"));
                }
                user.setEmail(request.getEmail());
            }

            if (request.getPhone() != null && !request.getPhone().equals(user.getPhone())) {
                if (userService.existsByPhone(request.getPhone())) {
                    return ResponseEntity.badRequest().body(Map.of("success", false, "message", "手机号已被注册"));
                }
                user.setPhone(request.getPhone());
            }

            if (request.getNewPassword() != null && !request.getNewPassword().isEmpty()) {
                user.setPassword(request.getNewPassword());
            }

            user.setUpdateTime(LocalDateTime.now());
            userService.updateUser(user);

            // 更新session中的用户信息
            session.setAttribute("user", user);

            return ResponseEntity.ok(Map.of("success", true, "message", "更新成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("success", false, "message", "更新失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/conversations/clear-all")
    public ResponseEntity<?> clearAllConversations(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }

        try {
            // 获取用户所有对话并逐个删除 - 使用新的方法
            ConversationListResponse conversations = conversationService.getUserConversationsResponse(user.getId(), 1, 1000);
            for (var conversation : conversations.getConversations()) {
                conversationService.deleteConversation(user.getId(), conversation.getId());
            }

            return ResponseEntity.ok(Map.of("success", true, "message", "所有对话已清空"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("success", false, "message", "清空失败: " + e.getMessage()));
        }
    }

    @Data
    public static class UpdateUserRequest {
        private String username;
        private String email;
        private String phone;
        private String currentPassword;
        private String newPassword;
    }
}